package com.cbtx.utils

import android.app.Application
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.util.Log
import androidx.core.content.FileProvider
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import java.io.*
import java.nio.charset.Charset

/**
 * author : joker.peng
 * e-mail : joker@fiture.com
 * date   : 2021/7/7 12:39 AM
 * desc   :
 */
object InstallApkUtil {
    private val TAG = "InstallApkUtil"

    /**
     * 执行具体的静默安装逻辑，需要手机ROOT。
     *
     * @param apkPath 要安装的apk文件的路径
     * @return 安装成功返回true，安装失败返回false。
     */
    fun installSilent(apkPath: String): Boolean {
        var result = false
        var dataOutputStream: DataOutputStream? = null
        var inputStream: BufferedReader? = null
        try {
            Log.d(TAG, "pm install -r $apkPath")
            // 申请su权限
            val process = Runtime.getRuntime().exec("su")
            dataOutputStream = DataOutputStream(process.outputStream)
            // 执行pm install命令
            val command = "pm install -r $apkPath\n"
            dataOutputStream.write(command.toByteArray(Charset.forName("utf-8")))
            dataOutputStream.flush()
            dataOutputStream.writeBytes("exit\n")
            dataOutputStream.flush()
            process.waitFor()
            inputStream = BufferedReader(InputStreamReader(process.inputStream))
            var msg = ""
            var line: String
            // 读取命令的执行结果
            while (inputStream.readLine().also { line = it } != null) {
                msg += line
            }

//            LogUtil.d("install msg:"+msg);

            //LogUtils.d("pm install msg-->" + msg);
            if (msg.contains("Success")) {
                result = true
            }
        } catch (e: Exception) {
            e.printStackTrace()

//            ToastUtil.showToast("" + e);
        } finally {
            //LogUtils.d("pm install finally()");
            try {
                dataOutputStream?.close()
                inputStream?.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        LogUtils.d("installSilent result  $result")
        return result
    }

    /**
     * 判断手机是否拥有Root权限。
     *
     * @return 有root权限返回true，否则返回false。
     */
    fun isRoot(): Boolean {
        var bool = false
        try {
            bool = File("/system/bin/su").exists() || File("/system/xbin/su").exists()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return bool
    }


    //静默卸载
    fun uninstallSlient(PACKAGE_NAME: String) {
        val cmd = "pm uninstall $PACKAGE_NAME"
        var process: Process? = null
        var os: DataOutputStream? = null
        var successResult: BufferedReader? = null
        var errorResult: BufferedReader? = null
        var successMsg: StringBuilder? = null
        var errorMsg: StringBuilder? = null
        try {
            process = Runtime.getRuntime().exec("su")
            os = DataOutputStream(process.outputStream)
            os.write(cmd.toByteArray())
            os.writeBytes("\n")
            os.writeBytes("exit\n")
            os.flush()

            //执行命令
            process.waitFor()

            //获取返回结果
            successMsg = StringBuilder()
            errorMsg = StringBuilder()
            successResult = BufferedReader(InputStreamReader(process.inputStream))
            errorResult = BufferedReader(InputStreamReader(process.errorStream))
            var s: String?
            while (successResult.readLine().also { s = it } != null) {
                successMsg.append(s)
            }
            while (errorResult.readLine().also { s = it } != null) {
                errorMsg.append(s)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            try {
                os?.close()
                process?.destroy()
                successResult?.close()
                errorResult?.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        ToastUtils.showShort("已卸载成功")
        //显示结果
    }


    fun getVersionName(context: Application): String? {
        // 获取packagemanager的实例
        try {
            val packageManager = context.packageManager
            // getPackageName()是你当前类的包名，0代表是获取版本信息
            val packInfo = packageManager.getPackageInfo(context.packageName, 0)
            return packInfo.versionName
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return ""
    }


    /**
     * 版本号比较
     *
     * @param version1
     * @param version2
     * @return
     */
    fun compareVersion(version1: String, version2: String): Int {
        if (version1 == version2) {
            return 0
        }
        val version1Array = version1.split("\\.".toRegex()).toTypedArray()
        val version2Array = version2.split("\\.".toRegex()).toTypedArray()
        LogUtils.d("version1Array==" + version1Array.size)
        LogUtils.d("version2Array==" + version2Array.size)
        var index = 0
        // 获取最小长度值
        val minLen = Math.min(version1Array.size, version2Array.size)
        var diff = 0
        // 循环判断每位的大小
        LogUtils.d("verTag2=2222=" + version1Array[index])
        while (index < minLen
            && version1Array[index].toInt() - version2Array[index].toInt().also { diff = it } == 0
        ) {
            index++
        }
        return if (diff == 0) {
            // 如果位数不一致，比较多余位数
            for (i in index until version1Array.size) {
                if (version1Array[i].toInt() > 0) {
                    return 1
                }
            }
            for (i in index until version2Array.size) {
                if (version2Array[i].toInt() > 0) {
                    return -1
                }
            }
            0
        } else {
            if (diff > 0) 1 else -1
        }
    }


    private fun execLinuxCommand() {
        val cmd = "sleep 120; am start -n com.cbtx.tablet.activity.MainActivity"
        //Runtime对象
        val runtime = Runtime.getRuntime()
        try {
            val localProcess = runtime.exec("su")
            val localOutputStream = localProcess.outputStream
            val localDataOutputStream = DataOutputStream(localOutputStream)
            localDataOutputStream.writeBytes(cmd)
            localDataOutputStream.flush()
            //            Logger.e("设备准备重启");
        } catch (e: IOException) {
//            Logger.i(TAG+"strLine:"+e.getMessage());
            e.printStackTrace()
        }
    }


    /**
     * 打开安装包
     *
     * @param mContext
     * @param fileUri
     */
    fun openAPKFile(mContext: Context, fileUri: String?) {

        // 核心是下面几句代码
        if (null != fileUri) {
            try {
                val intent = Intent(Intent.ACTION_VIEW)
                val apkFile = File(fileUri)
                //兼容7.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
                    val contentUri =
                        FileProvider.getUriForFile(mContext, mContext.packageName + ".FileProvider", apkFile)
                    intent.setDataAndType(contentUri, "application/vnd.android.package-archive")
                } else {
                    intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive")
                    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                }
                if (mContext.packageManager.queryIntentActivities(intent, 0).size > 0) {
                    mContext.startActivity(intent)
                }
            } catch (e: Throwable) {
                e.printStackTrace()
                //                LogUtils.d("e  :  " + e);
            }
        }
    }
}